package com.zhidao.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhidao.backend.annotation.LoginToken;
import com.zhidao.backend.annotation.PassToken;
import com.zhidao.backend.common.*;
import com.zhidao.backend.entity.Comment;
import com.zhidao.backend.entity.LoginUser;
import com.zhidao.backend.entity.SubComment;
import com.zhidao.backend.entity.User;
import com.zhidao.backend.exception.BusinessException;
import com.zhidao.backend.service.*;
import com.zhidao.backend.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * 用户请求控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IOssService ossService;

    @Resource
    private IFollowService followService;

    @Resource
    private ICommentService commentService;

    @Resource
    private ISubCommentService subCommentService;

    @Resource
    private IVerifyService verifyService;

    /**
     * 用户注册发送邮箱验证码
     * @param mail : 用户用以注册的邮箱
     * @return : 请求结果，验证码
     */
    @PassToken
    @GetMapping("/sendIC")
    public Result<Integer> SendIC(@RequestParam(name = "mail") String mail) {
        if (mail == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        return Result.success(verifyService.sendSimpleMail(mail));
    }

    /**
     * 用户注册
     * @param registerRequest : 注册请求
     * @return : 请求结果
     */
    @PassToken
    @PostMapping("/register")
    public Result<?> userRegister(@RequestBody RegisterRequest registerRequest) {
        if (registerRequest == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.register(registerRequest);
        return Result.success();
    }

    /**
     * 用户登录
     * @param loginRequest : 登录请求
     * @return : 请求结果
     */
    @PassToken
    @PostMapping("/login")
    public Result<LoginUser> userLogin(@RequestBody LoginRequest loginRequest) {
        if (loginRequest == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        User res = userService.login(loginRequest);
        List<Long> followedIds = followService.getSubscribeList(res.getId());
        String token = JwtUtil.createToken(res);
        LoginUser loginUser = new LoginUser();
        loginUser.setId(res.getId());
        loginUser.setToken(token);
        loginUser.setUser(res);
        loginUser.setFollowedIds(followedIds);
        return Result.success(loginUser);
    }

    /**
     * 账号注销
     * @param id : 账号id
     * @return : 请求结果
     */
    @LoginToken
    @GetMapping("/delete")
    public Result<?> userDelete(@RequestParam(name = "id") Long id) {
        if (id == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(id);
        userService.delete(id);
        return Result.success();
    }

    /**
     * 获取用户信息
     * @param id : 账号id
     * @return : 请求结果
     */
    @PassToken
    @GetMapping("/get/userinfo")
    public Result<User> getUserInfo(@RequestParam(name = "id") Long id) {
        if (id == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        User user = userService.getUserInfo(id);
        return Result.success(user);
    }

    /**
     * 更新用户信息
     * @param updateRequest : 更新请求
     * @return : 请求结果
     */
    @LoginToken
    @PostMapping("/update")
    public Result<?> userUpdate(@RequestBody UpdateRequest updateRequest) {
        if (updateRequest == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(updateRequest.getId());
        userService.updateProfile(updateRequest);
        return Result.success();
    }

    /**
     * 修改密码
     * @param changePasswordRequest : 修改密码请求
     * @return : 请求结果
     */
    @LoginToken
    @PostMapping("/change/password")
    public Result<?> changePassword(@RequestBody ChangePasswordRequest changePasswordRequest) {
        if (changePasswordRequest == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(changePasswordRequest.getId());
        userService.changePassword(changePasswordRequest);
        return Result.success();
    }

    /**
     * 上传头像
     * @param uploadImageRequest : 上传请求
     * @return : 请求结果
     */
    @LoginToken
    @PostMapping("/upload/avatar")
    public Result<String> userUploadAvatar(UploadImageRequest uploadImageRequest) {
        if (uploadImageRequest == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(uploadImageRequest.getId());
        String url = ossService.uploadImage(uploadImageRequest.getFile());
        userService.updateAvatar(uploadImageRequest.getId(), url);
        return Result.success(url);
    }

    /**
     * 关注用户
     * @param followRequest : 关注请求
     * @return : 请求结果
     */
    @LoginToken
    @PostMapping("/follow")
    public Result<?> userFollow(@RequestBody FollowRequest followRequest) {
        if (followRequest == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(followRequest.getFollowerId());
        userService.existUser(followRequest.getBloggerId());
        userService.existUser(followRequest.getFollowerId());
        followService.follow(followRequest);
        userService.follow(followRequest.getFollowerId());
        userService.beFollowed(followRequest.getBloggerId());
        return Result.success();
    }

    /**
     * 取消关注
     * @param followRequest : 取消关注请求
     * @return : 请求结果
     */
    @LoginToken
    @PostMapping("/unfollow")
    public Result<?> userUnfollow(@RequestBody FollowRequest followRequest) {
        if (followRequest == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(followRequest.getFollowerId());
        userService.existUser(followRequest.getBloggerId());
        userService.existUser(followRequest.getFollowerId());
        followService.unfollow(followRequest);
        userService.unfollow(followRequest.getFollowerId());
        userService.beUnfollowed(followRequest.getBloggerId());
        return Result.success();
    }

    /**
     * 获取关注列表
     * @param id : 用户id
     * @return : 请求结果
     */
    @LoginToken
    @GetMapping("/get/subscribe")
    public Result<List<User>> getSubscribe(@RequestParam(name = "id") Long id) {
        if (id == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(id);
        List<Long> subscribeIdList = followService.getSubscribeList(id);
        if (subscribeIdList == null || subscribeIdList.size() == 0) {
            return Result.success(new ArrayList<>());
        }
        List<User> subscribeList = new ArrayList<>();
        for (Long bloggerId : subscribeIdList) {
            subscribeList.add(userService.getUserInfo(bloggerId));
        }
        return Result.success(subscribeList);
    }

    /**
     * 根据单个关键词搜索用户
     * @param keyword : 关键词
     * @return : 搜索结果
     */
    @PassToken
    @GetMapping("/search")
    public Result<List<User>> searchUser(@RequestParam(name = "keyword") String keyword) {
        if (StringUtils.isBlank(keyword)) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        List<User> res = userService.search(keyword);
        return Result.success(res);
    }

    /**
     * 用户签到
     * @param id : 用户id
     * @return : 请求结果
     */
    @LoginToken
    @GetMapping("/sign")
    public Result<?> userSignIn(@RequestParam(name = "id") Long id) {
        if (id == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(id);
        userService.signIn(id);
        return Result.success();
    }
    /**
     * 用户删除评论
     * @param deleteCommentRequest : 删评论请求
     * @return : 请求结果
     */
    @LoginToken
    @PostMapping("/comment/delete")
    public Result<?> deleteComment(@RequestBody DeleteCommentRequest deleteCommentRequest) {
        if (deleteCommentRequest == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(deleteCommentRequest.getUserId());
        Long userId=deleteCommentRequest.getUserId();
        Long commentId=deleteCommentRequest.getCommentId();
        Comment comment = commentService.getCommentById(commentId);
        if(userId.equals(comment.getUserId())||userService.isAdministrator(userId)) {
            commentService.deleteComment(commentId);
            return Result.success();
        } else {
            throw new BusinessException(StatusCode.REJECT.getCode(), "无权限删除");
        }
    }

    /**
     * 用户对路线进行评论
     * @param commentToRouteRequest : 评论请求
     * @return : 用户id
     */
    @LoginToken
    @PostMapping("/comment/release")
    public Result<Long> commentToRoute(@RequestBody CommentToRouteRequest commentToRouteRequest) {
        if (commentToRouteRequest == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(commentToRouteRequest.getCommentatorId());
        return Result.success(commentService.commentToRoute(commentToRouteRequest));
    }
    /**
     * 用户删除楼中楼
     * @param deleteSubCommentRequest : 删楼中楼请求
     * @return : 请求结果
     */
    @LoginToken
    @PostMapping("/subcomment/delete")
    public Result<?> deleteSubComment(@RequestBody DeleteSubCommentRequest deleteSubCommentRequest) {
        if (deleteSubCommentRequest == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(deleteSubCommentRequest.getUserId());
        Long userId=deleteSubCommentRequest.getUserId();
        Long commentId=deleteSubCommentRequest.getSubCommentId();
        SubComment subComment = subCommentService.getSubCommentById(commentId);
        if(userId.equals(subComment.getCId())||userService.isAdministrator(userId)) {
            subCommentService.deleteSubComment(commentId);
            return Result.success();
        } else {
            throw new BusinessException(StatusCode.REJECT.getCode(), "无权限删除");
        }
    }
    /**
     * 用户对路线进行评论
     * @param subCommentRequest : 评论请求
     * @return : 用户id
     */
    @LoginToken
    @PostMapping("/subcomment/release")
    public Result<Long> subComment(@RequestBody SubCommentRequest subCommentRequest) {
        if (subCommentRequest == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(subCommentRequest.getCommentatorId());
        return Result.success(subCommentService.subCommentAction(subCommentRequest));
    }
    /**
     * 管理员封禁用户
     * @param banUserRequest : 封禁用户请求
     * @return : 请求结果
     */
    @LoginToken
    @PostMapping("/admin/banUser")
    public Result<?> banUser(@RequestBody BanUserRequest banUserRequest) {
        if (banUserRequest == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(banUserRequest.getBanner());
        userService.banUser(banUserRequest);
        return Result.success();
    }
    /**
     * 管理解封用户
     * @param unsealRequest : 解封用户请求
     * @return : 请求结果
     */
    @LoginToken
    @PostMapping("/admin/unsealUser")
    public Result<?> unsealUser(@RequestBody UnsealRequest unsealRequest) {
        if (unsealRequest == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(unsealRequest.getAdminId());
        userService.unsealUser(unsealRequest);
        return Result.success();
    }
    /**
     * 管理员获取用户列表
     * @param id: 管理员id
     * @return : 用户列表
     */
    @LoginToken
    @GetMapping("/admin/getUserList")
    public Result<List<User>> getUserList(@RequestParam(name = "id") Long id) {
        if (id == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(id);
        if(!userService.isAdministrator(id)) {
            throw new BusinessException(StatusCode.REJECT.getCode(), "无权限");
        }
        return Result.success(userService.list(new QueryWrapper<User>().eq("banned", false)));
    }
    /**
     * 管理员获取封禁用户列表
     * @param id: 管理员id
     * @return : 用户列表
     */
    @LoginToken
    @GetMapping("/admin/getBannedUserList")
    public Result<List<User>> getBannedUserList(@RequestParam(name = "id") Long id) {
        if (id == null) {
            throw new BusinessException(StatusCode.PARAM_ERROR.getCode(), "请求参数为空");
        }
        userService.isBanned(id);
        if(!userService.isAdministrator(id)) {
            throw new BusinessException(StatusCode.REJECT.getCode(), "无权限");
        }
        return Result.success(userService.list(new QueryWrapper<User>().eq("banned", true)));
    }




}
